package com.wang.madness.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wang.madness.annotation.PassToken;
import com.wang.madness.customEnum.ResultCode;
import com.wang.madness.customResponse.SuccessResult;
import com.wang.madness.exception.ApiRuntimeException;
import com.wang.madness.pojo.User;
import com.wang.madness.service.UserService;
import com.wang.madness.utils.JwtUtil;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * (User)表控制层
 *
 * @author 王文君
 * @since 2020-11-08 13:49:46
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

  /**
   * 服务对象
   */
  private final UserService userService;

  private final JwtUtil jwtUtil;


  @Autowired
  public UserController(UserService userService, JwtUtil jwtUtil) {
    this.userService = userService;
    this.jwtUtil = jwtUtil;
  }

  @PassToken
  @PostMapping("/login")
  public SuccessResult<Object> login(@RequestBody User user, @RequestParam String loginType) {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name", user.getUserName())
        .or()
        .eq("user_email", user.getEmail())
        .or()
        .eq("user_cell_phone", user.getPhone());
    User currentUser = userService.getOne(wrapper);
    if (currentUser != null && user.getPassWord().equals(currentUser.getPassWord())) {
      String token = jwtUtil.createToken(currentUser);
      return new SuccessResult<>(loginType, ResultCode.LOGIN_SUCCESS, token);
    }
    return new SuccessResult<>(loginType,"error", ResultCode.LOGIN_FAILED);
  }

  @PassToken
  @PostMapping("/register")
  public ResponseEntity<Object> insert(@RequestBody @Valid User user) {
    try {
      userService.save(user);
      return new ResponseEntity<>("新增用户成功", HttpStatus.CREATED);
    } catch (Exception e) {
      return new ResponseEntity<>("新增用户失败" + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @GetMapping("/getUserInfo")
  public SuccessResult<User> auth(HttpServletRequest request) {
    String token = request.getHeader("token");
    String userId = jwtUtil.getAudience(token);
    User user = userService.getById(userId);
    return SuccessResult.ok(user);
  }

}